#!/bin/bash

# @brief, ubuntu下samba服务器安装配置脚本
# @autor, LinusZhao
# @email, cs86zhao@foxmail.com

# !1 查看系统是否已经安装,没有安装则执行安装
if [ -n "$(which samba)" ];then
    echo "The samba server has been installed on the system."
else
    exec_cmd sudo apt-get update
    exec_cmd sudo apt-get install samba samba-common
fi
# !2 配置
while true
do
    read -p "please input a file sharing directory:" directory
    if [ -n $directory ];then
        exec_cmd sudo mkdir $directory
        exec_cmd sudo chmod 777 $directory
        echo "samba share file test" > $directory/test.txt
        break 
    else
        continue
    fi
done

conf_file=/etc/samba/smb.conf
if [ -f $conf_file ];then
    sudo echo "[samba]" >> $conf_file
    sudo echo "  path = $directory" >> $conf_file
    sudo echo "  create mask = 0700" >> $conf_file
    sudo echo "  available = yes" >> $conf_file
    sudo echo "  public = yes" >> $conf_file
    sudo echo "  browseable = yes" >> $conf_file
    sudo echo "  writable = yes" >> $conf_file
    exec_cmd tail $conf_file -n 7
else
    echo "file $conf_file no found!"
fi

exec_cmd sudo service smbd restart
echo "samba installation configuration complete"
tftp_status=$(exec_cmd sudo service smbd status |grep 'running')
echo $tftp_status

# 定义一个执行命令函数,加返回状态判断,执行错误直接退出整个脚本
# 用法说明: exec_cmd sudo apt-get install tftp-hpa
exec_cmd() {
    local cmd=$*
    echo $cmd
    $cmd
    local ret=$?
    if [ $ret -eq 0 ];then
        echo "$cmd successfully."
    else
        echo "$cmd fail ret=$ret."
        # return $ret
        exit $ret
    fi
}